var sqlite3 = require('sqlite3').verbose(),
	config = require('../config'),
	db = new sqlite3.Database(config.db_filename);

function getSensorType(id_sensor, callback) {	
	db.get("SELECT org, func, type FROM enocean WHERE id_sensor = " + id_sensor, function (err, row) {
	if (row == undefined) {
		//console.log('sensor not in database');
	} else {
			callback(row.org,row.func,row.type);
	}
});
}

/*
 * param data : should contain an 'id' attribute
 *   
 */
function storeData(data) {
		var d = JSON.stringify(data);
    db.run("INSERT INTO data VALUES ($id, datetime('now'), $data)", {
		    $id: data.id,
				$data: d
		}, function(error) { //'error' callback
		    if (error) console.log(error.toString());
		});
}

/*
 * param data : should have following keys :
 * { id: , org: , func: , type: , desc: }
 */
function storeSensor(data) {
    db.serialize(function() {
			db.run("INSERT INTO enocean VALUES ($id, $org, $func, $type, $desc)", {
					$id: data.id,
					$org: data.org,
					$func: data.func,
					$type: data.type,
					$desc: data.desc
			}, function(error) { //'error' callback
					if (error) console.log(error.toString());
			});

			//default action is set
			enocean_id = "enocean_" + data.id.toString();
			db.run("INSERT INTO source VALUES ($id, 'stats/record_enocean')", {
				$id: enocean_id
			}, function(error) {
				if (error) console.log(error.toString());
			});
		});
}

function insertAction(source, action) {
	db.run("INSERT INTO source VALUES ($id, $action)", {
		$id: source,
		$action: action
	}, function(error) {
	if (error) console.log(error.toString());
	});
}

function getSensorActions(id_source, callback) {
	db.all("SELECT action FROM source WHERE id_source = $id", {
		$id: id_source
	}, function(err, rows) {

	if (rows == undefined) {
		console.log('no action related to the source with id '+id_source);
	} else {
		if (rows.length > 0) {


			var actions = [];

			for (var i = 0; i < rows.length; i++) {
				actions.push(rows[i]['action']);
			}

			callback(actions);

			} else console.log('Warning : no actions linked to the sensor with id ' + id_source);
		}
	});
};


function createDatabase() {
	db.serialize(function() {
		db.run("CREATE TABLE enocean (id_sensor INTEGER, org INTEGER, func INTEGER, type INTEGER, desc TEXT)");
		db.run("CREATE TABLE source (id_source TEXT, action TEXT)");
		db.run("CREATE TABLE data(id_sensor INTEGER, date DATETIME, data TEXT)");
		db.run("CREATE TABLE andro_devices(id_gcm INTEGER)");

		db.run("INSERT INTO source VALUES ('__teachin', 'stats/learn_enocean')");
	});
};

function storeDeviceID(deviceId) {
	db.serialize(function() {
		db.run("INSERT INTO andro_devices VALUES (?) ", deviceId);
	});
}

function removeDeviceID(deviceId) {
	db.serialize(function() {
		db.run("DELETE FROM andro_devices WHERE id_gcm=? ", deviceId);
	});
}

/*
 * Usage: give it a callback function like this: callback(registrationIds) and
 * registrationIds is an array.
 */
function getDevicesIDs(callback) {
	var retourSQL = {};
	var registrationIds = new Array();

	var callbackSQL = function() {
		for (var i = 0; i < retourSQL.length; i++) {
			var obj = retourSQL[i];
			for (var key in obj) {
				if (key == "id_gcm")  {
					registrationIds.push('' + obj[key]);
				}
			}
		}

		callback(registrationIds);
	}

	db.all("SELECT rowid,id_gcm FROM andro_devices", function(err, rows) {
		if (rows != undefined) {
			retourSQL = rows;
		} else {
			retourSQL['error'] = 'Error, could not fetch android devices data...';
			console.log(err);
		}
		callbackSQL();
	});
}

exports.getSensorType = getSensorType;
exports.storeData = storeData;
exports.storeSensor = storeSensor;
exports.getSensorActions = getSensorActions;
exports.createDatabase = createDatabase;
exports.storeDeviceID = storeDeviceID;
exports.removeDeviceID = removeDeviceID;
exports.getDevicesIDs = getDevicesIDs;
exports.insertAction = insertAction;
